<!-- 
  某类型店铺 如淘宝
-->
<template>
  <div class="typeShop">
    <div class="btnBox" v-if="list&&list.length>0">
      <span @click="isManage = !isManage" class="btnManage">{{
        isManage ? "退出管理" : "管理"
      }}</span>
    </div>
    <!-- 商品列表 -->
    <div class="list" v-if="list && list.length > 0">
      <div class="" v-for="(itemJ, idxJ) in list" :key="idxJ">
        <shop
          :shopItem="itemJ"
          @del="delSure($event, idxJ)"
          @handleSelectAllChild="handleSelectAllChild"
          ref="shop"
          :isManage="isManage"
        ></shop>
      </div>
    </div>
    <div v-else class="noData">
      <noData></noData>
    </div>

    <!-- 总价 -->
    <div class="total" v-if="list">
      <van-checkbox
        v-model="selectAll"
        :icon-size="iconSize"
        @click="handleSelectAll"
        >全选</van-checkbox
      >
      <span
        >总价：<b>￥</b><b class="price">{{ total }}</b></span
      >
      <div class="btn" @click="handleSubmit">提交订单</div>
    </div>
  </div>
</template>

<script>
import { Dialog, Toast } from "vant";
import shop from "@/components/cart/shop.vue";
import noData from "@/components/no-data.vue";
import localStore from "@/libs/localstore";
import config from "@/libs/config";
export default {
  components: {
    shop,
    noData,
  },
  props: {
    // @currentTab 上一级点击选项卡进行切换商铺
    currentTab: {
      type: String,
    },
  },
  data() {
    return {
      host: config.host,
      iconSize: "18px",
      selectAll: false,
      isManage: false,
      list: [],
      returnData: "", // 提交表单返回的数据
      submitData: [
        //提交订单的数据
        {
          type: "TB",
          shopList: [],
        },
      ],
      returnOrderId: "", //创建订单返回的id
    };
  },
  computed: {
    round() {
      return (num, n) => {
        return Math.round(num * Math.pow(10, n)) / Math.pow(10, n);
      };
    },
    total() {
      let total = [];
      if (this.list.length > 0) {
        this.list.forEach((item) => {
          if (item.list && item.list.length > 0) {
            item.list.forEach((itemJ) => {
              if (itemJ.isChecked) {
                total.push(itemJ.count * itemJ.price);
              }
            });
          }
        });
        return this.round(
          total &&
            total.length > 0 &&
            total.reduce((prev, next) => prev + next),
          1
        );
      } else {
        return 0
      }
    },
  },
  mounted() {
    this.init();
  },
  methods: {
    copy() {
      if (!this.returnData) return;
      // 获取需要复制的文本内容
      var textToCopy = this.returnData; // 在此处输入你想要复制的文本内容

      // 创建一个临时元素并设置其值为需要复制的文本内容
      var tempElement = document.createElement("textarea");
      tempElement.value = textToCopy;
      document.body.appendChild(tempElement);

      // 选中临时元素的所有文本内容
      tempElement.select();
      tempElement.setSelectionRange(0, 99999); /* For mobile devices */

      // 复制选中的文本内容到剪贴板
      document.execCommand("copy");

      // 移除临时元素
      document.body.removeChild(tempElement);
      Dialog.alert({
        title: "标题",
        message: "链接地址已复制到剪贴板",
      }).then(() => {});
    },
    init() {
      this.list = JSON.parse(localStore.getItem("cartTaobao"));
    },
    delSure(sku_id, idx) {
      // 删除确认
      this.remove(this.list[idx]["list"], sku_id);
      // 如果当前店铺已经没有商品在购物车内了，删除当前商铺
      if (this.list[idx]["list"].length === 0) {
        this.list.splice(idx, 1);
      }
      localStore.setItem("cartTaobao", JSON.stringify(this.list));
      Toast.success("删除成功");
    },
    //数组删除:
    // 1. 用于管理操作的删除
    remove(arr, val) {
      var index = arr.findIndex((item) => item.sku_id == val);
      if (index > -1) {
        arr.splice(index, 1);
      }
    },
    // 通过获取子级全选状态来更新此处
    // 只有所有子级的selectAll==true时，将此处的selectAll更新为true
    handleSelectAllChild() {
      this.selectAll =
        this.$refs.shop && this.$refs.shop.every((child) => child.selectAll);
    },
    // 提交订单
    handleSubmit() {
      // 取出所有isChecked的数据，进行提交
      const newData = this.list.map((item) => {
        let list = item.list && this.getIsChecked(item.list);
        if (list && list.length > 0) {
          return {
            id: item.id,
            goodsList: list,
          };
        }
      });
      if (newData && newData.length === 0) {
        Toast.fail("请选择商品");
        return;
      }
      // console.log(newData.filter((item) => item));
      // 需要传后台的参数内容
      this.submitData[0].shopList = newData.filter((item) => item);
      // console.log(this.submitData);
      this.$store.commit("setShowLoading", true);
      var myHeaders = new Headers();
      myHeaders.append("User-Agent", "Apifox/1.0.0 (https://apifox.com)");
      myHeaders.append("Content-Type", "application/json");
      var requestOptions = {
        method: "POST",
        headers: myHeaders,
        body: JSON.stringify(this.submitData),
        redirect: "follow",
      };
      fetch(`${this.host}/api/v1/order`, requestOptions)
        .then((res) => res.json())
        .then((result) => {
          if (result.statusCode == 200) {
            this.returnOrderId = result.data;
            Toast.success("提交成功");
            this.returnData = `${this.host}/api/v1/order/${this.returnOrderId}`;
            this.copy();
            // console.log("detail", this.returnData);
            // 只保留购车中未提交数据
            // this.returnSubmitData();
            this.$store.commit("setShowLoading", false);
          }
        })
        .catch((error) => console.log("error", error));
    },
    // 只保留购车中未提交数据
    returnSubmitData() {
      const remainData = this.list.map((item) => {
        return item["list"].filter((sub) => {
          return !sub.isChecked;
        });
      });
      if (remainData.length == 1 && remainData[0].length == 0) {
        remainData.length = 0;
      }
      // 重新保存数据
      localStore.setItem("cartTaobao", JSON.stringify(remainData));
      this.init();
    },

    // 获取isChecked的所有内容
    getIsChecked(list) {
      if (list && list.length == 0) return [];
      let arr = list.filter((item) => item.isChecked);
      if (arr.length == 0) return [];
      return arr.map((item) => {
        return {
          id: item.id,
          count: item.count,
          sku: item.sku_id,
        };
      });
    },
    // 全选
    handleSelectAll() {
      if (this.list.length === 0) return;
      if (!this.selectAll) {
        console.log("全不选");
        this.list.forEach((item, idx) => {
          if (item.list && item.list.length > 0) {
            /// 更改子组件全选按钮状态
            this.$refs.shop &&
              this.$refs.shop.length > 0 &&
              this.$refs.shop[idx].chooseAllNot();
          }
        });
      } else {
        console.log("全选");
        this.list.forEach((item, idx) => {
          if (item.list && item.list.length > 0) {
            /// 更改子组件全选按钮状态
            this.$refs.shop &&
              this.$refs.shop.length > 0 &&
              this.$refs.shop[idx].chooseAll();
          }
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.typeShop {
  margin-top: -38px;
}
.list {
  margin-top: 20px;
}
.btnBox {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  .btnManage {
    cursor: pointer;
    user-select: none;
  }
}
.total {
  position: fixed;
  width: 100%;
  left: 0;
  right: 0;
  bottom: 80px;
  background-color: #fff;
  z-index: 99;
  height: 80px;
  padding: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  .price {
    font-size: 20px;
  }
  .btn {
    $h: 50px;
    $c: #ffa351;
    // border:2px solid #ffa351;
    background-color: $c;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #fff;
    font-weight: bold;
    border-radius: $h;
    height: $h;
    width: 140px;
    cursor: pointer;
  }
}
</style>
